package com.engc.common.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.engc.common.bean.SysUserInfo;
import com.engc.common.service.BaseService;
import com.engc.common.utils.BaseUtils;
import com.engc.common.utils.Constant;
import com.engc.common.utils.MD5Util;
import com.engc.common.utils.ReadProperties;

/**
 * 系统核心类
 * 
 * @author guzhixiong
 * 
 */
@Service
public class SystemService {
	private static final Log logger = LogFactory.getLog(SystemService.class);
	BaseService baseService;
	// 超级管理员ID
	private static final String AdminUserID = new ReadProperties("config/Global.properties").getValue("AdminUserID");
	// 超级管理员角色ID
	private static final String AdminRoleID = new ReadProperties("config/Global.properties").getValue("AdminRoleID");
	// 全局，是否启用权限
	private static final boolean EnabledPermission = Boolean.valueOf(new ReadProperties("config/Global.properties").getValue("EnabledPermission"));

	/**
	 * 判断指定用户是否是管理员
	 * 
	 * @param userid
	 * @return
	 */
	public boolean IsAdministrator(SysUserInfo user) {
		if (!"".equals(AdminUserID) && AdminUserID.equals(user.getUserid())) {
			return true;
		}
		// 如果没有配置超级管理员角色
		if ("".equals(AdminRoleID)) {
			return false;
		}
		// 判断当前用户角色是否包含超级管理员角色
		return AdminRoleID.equals(user.getRoleid());
	}

	/**
	 * 验证用户名密码
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public SysUserInfo validateLogin(String username, String password) {
		try {
//			username = "a";
//			password = "1";
			//此处针对临时老E卡通(非云平台)数据库修改
			String sql = "SELECT t.* FROM stb_customer t where t.usercode=? and t.password=?";
			//String sql = "select t1.*,t2.orgname  from stb_customer t1,stb_org t2  where (t1.userid=? or t1.usercode=? ) and t1.password=?  and substr(t1.orgid,1,6) = t2.orgid and t2.status=1  ";
			List<Map<String, Object>> list = baseService.Query(sql,
					new Object[] { username,password});
			if (list == null || list.isEmpty()) {
				return null;
			}
			Map<String, Object> map = list.get(0);
			SysUserInfo info = new SysUserInfo();
			info.setUserid(map.get("usercode") == null ? null : String.valueOf(map.get("usercode")));
			info.setUsercode(String.valueOf(map.get("usercode")));
			info.setUsername(String.valueOf(map.get("username")));
//			info.setCurOrgid("100000");
//			info.setOrgid("100000");
//			info.setDataOrgid("100000");
//			info.setAdminFlag(true);
//			info.setRoleid(String.valueOf(map.get("role")));
//			info.setRoleName(String.valueOf(map.get("rolename")));
			return info;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 用户登录
	 * 
	 * @param username
	 * @return
	 */
	public boolean doLoginVlidate(String username, String password) {
		Map<String, Object> userinfo = baseService.Read(
				" select b.name as reaname,c.orgid,a.* from sys_user_info a  left join sys_volunteer_inf b on a.vid=b.id left join sys_user_apply c "
						+ " on a.id = c.createby_id and c.status = 2 and a.name=? and a.password=?", username, password);
		boolean isLoginSuccess = !userinfo.isEmpty();
		if (isLoginSuccess) {
			List<Map<String, Object>> roles = baseService.Query(" select role_id,sort from sys_user_role where user_id=? order by sort desc,id ",
					userinfo.get("id"));
			StringBuffer sb = new StringBuffer();
			for (Map<String, Object> role : roles) {
				sb.append(role.get("role_id")).append(",");
			}
			sb = sb.deleteCharAt(sb.lastIndexOf(","));
			String currentroles = sb.toString();
			logger.info("系统信息：" + userinfo.get("name") + " 登录系统");
		}
		return isLoginSuccess;
	}

	/**
	 * 获取用户所有的有权限的菜单
	 * 
	 * @param userid
	 * @return
	 */
	public List<Map<String, Object>> getUserMenus(SysUserInfo sysuser) {
		// 如果没有启用权限控制，或者是管理员，直接获取全部菜单
		if (!EnabledPermission || IsAdministrator(sysuser)) {
			return BaseUtils.ArrayToTreeData(
					baseService.Query("SELECT a.*,a.menuname as text,a.menuicon as icon,a.menuid as id FROM sys_menu a order by a.menuorder"), "menuno",
					"menuparentno");
		}
		String userMenuSql = "select   menuid,menuid as id,menuno,menuparentno,menuname,menuname as text,menuurl,menuicon as icon from sys_menu where (menuid in(select distinct PrivilegeAccessKey "
				+ " from sys_acl  where PrivilegeMaster = 'user'  and PrivilegeMasterKey = ? "
				+ " and PrivilegeAccess = 'sys_menu'  and PrivilegeOperation = 1) "
				+ " or menuid in(select distinct PrivilegeAccessKey    from sys_acl "
				+ " where PrivilegeMaster = 'role'   and PrivilegeMasterKey=? "
				+ " and PrivilegeAccess = 'sys_menu'   and PrivilegeOperation = 1))  "
				+ " and menuid not in (select distinct PrivilegeAccessKey from sys_acl "
				+ " where PrivilegeMaster = 'user'  and PrivilegeMasterKey = ? "
				+ " and PrivilegeAccess = 'sys_menu' and PrivilegeOperation = 0) and menuparentno<>'0' order by menuorder";
		List<Map<String, Object>> privatemenus = baseService.Query(userMenuSql, sysuser.getUserid(), sysuser.getRoleid(), sysuser.getUserid());
		List<String> parentmenus = new ArrayList<String>();
		for (Map<String, Object> tempmenu : privatemenus) {
			if (!parentmenus.contains(tempmenu.get("menuparentno"))) {
				parentmenus.add(tempmenu.get("menuparentno").toString());
			}
		}
		// 匹配对应的root 菜单
		String rootMenuSql = "select * from sys_menu where menuparentno = '0'";
		List<Map<String, Object>> rootMenus = baseService.Query(rootMenuSql);
		List<Map<String, Object>> hasRootMenus = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> temp : rootMenus) {
			if (parentmenus.contains(temp.get("menuno"))) {
				hasRootMenus.add(temp);
			}
		}
		privatemenus.addAll(hasRootMenus);
		return BaseUtils.ArrayToTreeData(privatemenus, "menuno", "menuparentno");
	}

	/**
	 * 获取用户所有有权限的按钮
	 * 
	 * @param userid
	 */
	public Map<String, ArrayList> getUserButtons(SysUserInfo sysUser) {
		// 如果没有启用权限控制，或者是管理员，直接获取全部按钮

		List<Map<String, Object>> buttons = new ArrayList<Map<String, Object>>();
		if (!EnabledPermission || IsAdministrator(sysUser)) {
			buttons = baseService.Query("select * from sys_button order by btnid");
		} else {
			String pbuttonssql = "select * from sys_button where (btnid in(select distinct PrivilegeAccessKey "
					+ " from sys_acl where PrivilegeMaster = 'user'    and PrivilegeMasterKey = ?"
					+ "  and PrivilegeAccess = 'sys_button'  and PrivilegeOperation = 1) "
					+ "  or btnid in(select distinct PrivilegeAccessKey    from sys_acl " + "  where PrivilegeMaster = 'role'   and PrivilegeMasterKey=? "
					+ "  and PrivilegeAccess = 'sys_button'     and PrivilegeOperation = 1))  "
					+ "  and btnid not in (select distinct PrivilegeAccessKey    from sys_acl "
					+ "  where PrivilegeMaster = 'user'  and PrivilegeMasterKey =? "
					+ " and PrivilegeAccess = 'sys_button'  and PrivilegeOperation = 0) order by btnid";
			buttons = baseService.Query(pbuttonssql, sysUser.getUserid(), sysUser.getRoleid(), sysUser.getUserid());
		}
		HashMap<String, ArrayList> button = new HashMap<String, ArrayList>();
		for (Map<String, Object> temp : buttons) {
			if (button.containsKey(temp.get("menuno"))) {
				ArrayList list = button.get(temp.get("menuno"));
				list.add(temp);
				button.put(temp.get("menuno").toString(), list);
			} else {
				ArrayList list = new ArrayList();
				list.add(temp);
				button.put(temp.get("menuno").toString(), list);
			}
		}
		return button;
	}

	@Resource
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}

}
